package com.yimi.appstore.download2;

import com.yimi.appstore.R;
import com.yimi.appstore.YimiApplication;
import com.yimi.appstore.activity.MainActivity;
import com.yimi.appstore.download.DownloadTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class DownloadNotify {

	public static final String TAG = "DownloadNotify";
	private DownloadManager downloadManager;
	private DownloadNotify downloadNotify;
	private NotificationManager notificationManager;
	private Notification notification;
	private Context context;
	private int DOWNLOAD_NOTIFY = 1000;

	public DownloadNotify(Context context) {
		this.context = context;
		if (downloadNotify == null)
			notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		if (downloadManager == null)
			downloadManager = DownloadManager.getInstance(context);
	}

	public void nitify() {
		int downingCount = 0;
		for (DownloadJob job : YimiApplication.jobList) {
			int status = job.getJobStatus();
			if (status == DownloadManager.STATE_DOWNLOADING || status == DownloadManager.STATE_READY_DOWNLOAD
					|| status == DownloadManager.STATE_WAITING) {
				downingCount++;
			}
		}
		notification = new Notification(R.drawable.app_deafault, downingCount + "个应用正在下载", System.currentTimeMillis());
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		intent.setClass(context, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//		Intent i = new Intent(context, MainActivity.class);
		intent.putExtra("id", DOWNLOAD_NOTIFY);
		PendingIntent pi = PendingIntent.getActivity(context, DOWNLOAD_NOTIFY, intent, Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		notification.setLatestEventInfo(context, downingCount + "个应用正在下载", "点击查看详情", pi);
		notificationManager.notify(DOWNLOAD_NOTIFY, notification);
	}

	public void cancle() {
		int downingCount = 0;
		for (DownloadJob job : YimiApplication.jobList) {
			int status = job.getJobStatus();
			if (status == DownloadManager.STATE_DOWNLOADING || status == DownloadManager.STATE_READY_DOWNLOAD
					|| status == DownloadManager.STATE_WAITING) {
				downingCount++;
			}
		}
		if (downingCount == 0)
			notificationManager.cancel(DOWNLOAD_NOTIFY);
		else {
			notification = new Notification(R.drawable.app_deafault, downingCount + "个应用正在下载",
					System.currentTimeMillis());
			Intent i = new Intent(context, MainActivity.class);
			i.putExtra("id", DOWNLOAD_NOTIFY);
			PendingIntent pi = PendingIntent.getActivity(context, DOWNLOAD_NOTIFY, i, 0);
			notification.setLatestEventInfo(context, downingCount + "个应用正在下载", "点击查看详情", pi);
			notificationManager.notify(DOWNLOAD_NOTIFY, notification);
		}

	}
}
